package example.lec05;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class TestMain {
    public static void test0()
    {
        ExpressionParser parser = new SpelExpressionParser();
        //使用普通值类型表达式
        String str1 = (String) parser.parseExpression("'Hello Spring'").getValue();
        
        double pi = (Double) parser.parseExpression("3.1415926E+23").getValue();
        boolean flag = (Boolean) parser.parseExpression("true").getValue();
        Object obj = parser.parseExpression("null").getValue();

        System.out.println(str1);
        System.out.println(pi);
        System.out.println(flag);
        System.out.println(obj);
    }

    public static void test1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean_lec05.xml");
        //创建用于解析表达式的对象
        ExpressionParser ep=new SpelExpressionParser();
        //调用字符串方法表达式
        Expression e = ep.parseExpression("'hello'.concat(' spring')");
        String result1 = e.getValue().toString();
        System.out.println(result1);    
        
        //StandardEvaluationContext设值root对象
        User user=(User)context.getBean("user");
        //要计算user对象的username属性值，即计算user.username
        e = ep.parseExpression("username");
        StandardEvaluationContext ec = new StandardEvaluationContext();
        //将从Spring IoC容器中获取的user对象设值为ec的root对象
        ec.setRootObject(user);
        //计算表达式的值
        String username = (String) e.getValue(ec);
        System.out.println(username);
    }

    public static void test2()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean_lec05.xml");
        User2 user=(User2)context.getBean("user2");
        System.out.println(user);
    }

    public static void test3()
    {
        ApplicationContext context=new AnnotationConfigApplicationContext(User3.class);
        User3 user=(User3)context.getBean("user3");	
        System.out.println(user);;
    }

    public static void test4()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean_lec05.xml");
        User user=(User)context.getBean("USER123");
        System.out.println(user.getUsername() + user.getPassword());
    }
    
    public static void main(String[] args)
    {
        test0();
        test1();
        test2();
        test3();
    }
}
